package com.example.docking.httpXKY.httpSend;

import com.example.docking.httpXKY.dao.BaseRequestBody;
import com.example.docking.httpXKY.dao.CKYRequestBody;
import com.example.docking.httpXKY.dao.OrderListReqParam;
import com.example.docking.httpXKY.util.SignUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Slf4j
public class XKYClient {
    public static final String ERP_CODE = "ZY00001";
    private static final OkHttpClient client = new OkHttpClient();
    private static final Gson gson = new Gson();

    public static <T extends BaseRequestBody> String sendRequest(String url, T body) throws IOException {
        CKYRequestBody<T> requestBody = new CKYRequestBody<>(SignUtils.getCommon(), body);
        String json = gson.toJson(requestBody);
        System.out.println(url);
        System.out.println(json);
        log.info("请求url：{}，请求参数：{}", url, json);
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(json, MediaType.parse("application/json; charset=utf-8")))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response.code() + ": " + response.message());
            }
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                throw new IOException("Response body is null");
            }
            String result = responseBody.string();
            log.info("请求url：{}，返回结果：{}", url, result);
            return result;
        }
    }

    public static void main(String[] args) {
        String erpCode = "123"; // 替换为实际的ERP帐号
        OrderListReqParam orderListReqParam = new OrderListReqParam();
        orderListReqParam.setErpCode(erpCode);
        orderListReqParam.setStartDate(LocalDateTime.of(2025, 5, 20, 0, 0, 0).toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        orderListReqParam.setEndDate(LocalDateTime.of(2025, 5, 28, 0, 0, 0).toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        try {
            String response = sendRequest("https://openapi.xiekeyun.com/purchase/aftersale/list.json", orderListReqParam);
            System.out.println("Response: " + response);
        } catch (IOException e) {
            System.err.println("Error occurred while sending request: " + e.getMessage());
            e.printStackTrace();
        }
    }
}